const { log } = require("console");
const express = require("express")
const app = express();
const path = require("path");

//处理body请求体中间件
app.use(express.urlencoded())
app.use(express.json())


//cors跨域接口
app.get('/getInfo', (req, res) => {
    //所有请求都允许
    res.set("Access-Control-Allow-Origin", '*')
    //设置允许跨域的ip地址
    res.set("Access-Control-Allow-Origin", 'http://127.0.0.1:5500')
    //设置允许允许跨域的地址集合
    const allow = ['http://127.0.0.1:5500', 'http://127.0.0.1:5501']
    console.log(req.headers.origin);//拿到请求的来源地址
    if (allow.includes(req.headers.origin)) {
        res.set("Access-Control-Allow-Origin", req.headers.origin)
        
    }

    res.send({
        code: 10000,
        msg: "查询成功",
        data: {
            name: "李博",
            age: 18,
            sex: "男"
        }
    })
})


//jsonp请求接口
app.get('/getUser', (req, res) => {
    console.log(req.query);

    const {
        userId, cb
    } = req.query

    const data = {
        code: 10000,
        msg: "查询成功",
        data: {
            name: "李博",
            age: 18,
            sex: "男"
        }
    }
    res.send(`${cb}(${JSON.stringify(data)})`)

})


//查询学生信息接口
app.get("/user", (req, res) => {
    console.log("收到请求");
    const {
        userId
    } = req.query;


    //如果查询失败
    if (userId !== "001") {
        return res.send({
            code: 10001,
            msg: "查询失败",
            data: null
        })
    }


    //查询成功 响应
    res.send({
        code: 10000,
        msg: "查询成功",
        data: {
            name: "李博",
            age: 18,
            sex: "男"
        }
    })

})

app.listen(3000, () => {
    console.log("服务器请求成功 请访问 http://127.0.0.1:3000");
})